// 获取应用实例
const app = getApp();
const api = require('../../utils/api');
const healthApi = require('../../utils/api/health');

Page({
  data: {
    loading: true,
    assessments: [],
    noData: false,
    showDetail: false,
    selectedRisk: null,
    // 日期相关
    currentDate: '',
    today: '',           // YYYY-MM-DD 格式
    selectedDateStr: '', // YYYY-MM-DD 格式
    selectedDate: null,  // 存储选中的日期对象
    // 趋势数据
    trendData: {
      dates: [],
      values: [],
      categories: []
    },
    // 为simple-chart组件准备的图表数据
    chartData: [
      {
        name: "风险概率",
        color: "#5b8ef4",
        data: []
      }
    ],
    statistics: {
      avgRisk: "0",
      riskDistribution: {
        low: 0,
        medium: 0,
        high: 0
      }
    }
  },

  // 生命周期函数--监听页面加载
  onLoad: function(options) {
    this.initDates();
    this.loadAssessments();
  },

  // 页面显示时刷新数据
  onShow: function() {
    this.loadAssessments();
  },

  // 初始化日期
  initDates() {
    const now = new Date();
    const today = now.toISOString().split('T')[0];  // YYYY-MM-DD 格式
    const currentDate = this.formatDateToString(now);
    
    this.setData({
      today,
      selectedDateStr: today,
      currentDate,
      selectedDate: now
    });
  },

  // 格式化日期显示
  formatDateToString(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    return `${year}年${month}月`;
  },

  // 日期选择处理
  onSelectDate(e) {
    const date = e.detail.value;
    const selectedDate = new Date(date);
    const currentDate = this.formatDateToString(selectedDate);
    
    this.setData({
      currentDate,
      selectedDateStr: date,
      selectedDate
    }, () => {
      this.loadAssessments();
    });
  },

  // 加载评估记录
  loadAssessments: function() {
    this.setData({ loading: true });
    
    console.log('开始尝试获取风险评估记录...');
    // 返回Promise，用于处理下拉刷新
    return new Promise((resolve, reject) => {
      // 使用API获取风险评估记录
      healthApi.getRiskAssessments({ limit: 50 })
        .then(assessments => {
          console.log('API调用成功，获取到评估记录:', assessments);
          if (!assessments || assessments.length === 0) {
            console.log('没有找到风险评估记录');
            this.setData({
              loading: false,
              noData: true
            });
            resolve();
            return;
          }
          
          console.log('获取到原始风险评估数据:', assessments);
          
          try {
            const processedAssessments = assessments.map(item => {
              // 确保timestamp存在，优先使用measuredAt字段
              const timestamp = item.measuredAt || item.timestamp || new Date().toISOString();
              const date = new Date(timestamp);
              
              // 确保结果对象存在
              const result = item.result || {};
              
              // 确保概率值存在并有效
              const probability = result.probability !== undefined ? 
                result.probability : (item.probability !== undefined ? item.probability : 0);
              
              // 格式化风险百分比，确保是有效数字
              const riskPercentage = !isNaN(probability) ? 
                (probability * 100).toFixed(1) : "0.0";
              
              // 获取风险级别，确保存在有效值
              const riskLevel = result.riskLevel || item.riskLevel || '未知风险';
              
              // 判断风险级别的CSS类
              let riskClass = '';
              if (riskLevel === '低风险') {
                riskClass = 'low-risk';
              } else if (riskLevel === '中风险') {
                riskClass = 'medium-risk';
              } else {
                riskClass = 'high-risk';
              }
              
              // 确保日期格式化正确
              let formattedDate = '';
              let formattedTime = '';
              
              if (!isNaN(date.getTime())) {
                // 日期有效
                formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
                formattedTime = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
              } else {
                // 日期无效，使用当前日期时间
                const now = new Date();
                formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
                formattedTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
              }
              
              return {
                ...item,
                timestamp,
                formattedDate,
                formattedTime,
                riskPercentage,
                riskClass,
                probability,
                riskLevel
              };
            });
            
            console.log('处理后的风险评估数据:', processedAssessments);
            
            // 根据选中的月份过滤数据
            const filteredAssessments = this.filterAssessmentsByMonth(processedAssessments);
            
            // 获取最近10条记录用于趋势图
            const recentAssessments = [...filteredAssessments].slice(0, 10).reverse();
            
            // 处理趋势数据
            const dates = recentAssessments.map(item => {
              // 只保留月-日格式，如 "03-15"
              return item.formattedDate.slice(5);
            });
            
            const values = recentAssessments.map(item => {
              // 确保值是有效的数字
              const val = parseFloat(item.riskPercentage);
              return isNaN(val) ? 0 : val;
            });
            
            const categories = recentAssessments.map(item => {
              if (item.riskClass === 'low-risk') return 0;
              if (item.riskClass === 'medium-risk') return 1;
              return 2;
            });
            
            // 获取风险评估统计数据
            console.log('开始获取风险评估统计数据...');
            healthApi.getRiskAssessmentStats()
              .then(stats => {
                console.log('获取到风险评估统计数据:', stats);
                
                this.setData({
                  assessments: filteredAssessments,
                  noData: filteredAssessments.length === 0,
                  loading: false,
                  trendData: {
                    dates,
                    values,
                    categories
                  },
                  chartData: [
                    {
                      name: "风险概率",
                      color: "#5b8ef4",
                      data: values
                    }
                  ],
                  statistics: stats || {
                    avgRisk: "0",
                    riskDistribution: {
                      low: 0,
                      medium: 0,
                      high: 0
                    }
                  }
                });
                resolve();
              })
              .catch(error => {
                console.error('获取风险评估统计数据失败:', error);
                
                this.setData({
                  assessments: filteredAssessments,
                  noData: filteredAssessments.length === 0,
                  loading: false,
                  trendData: {
                    dates,
                    values,
                    categories
                  },
                  chartData: [
                    {
                      name: "风险概率",
                      color: "#5b8ef4",
                      data: values
                    }
                  ]
                });
                resolve();
              });
          } catch (error) {
            console.error('处理风险评估数据时出错:', error);
            this.setData({
              loading: false,
              noData: true
            });
            resolve();
          }
        })
        .catch(error => {
          console.error('获取风险评估记录失败:', error);
          this.setData({
            loading: false,
            noData: true
          });
          reject(error);
        });
    });
  },
  
  // 根据选择的月份过滤评估记录
  filterAssessmentsByMonth(assessments) {
    if (!this.data.selectedDate || !assessments || !assessments.length) {
      return [];
    }
    
    const targetYear = this.data.selectedDate.getFullYear();
    const targetMonth = this.data.selectedDate.getMonth() + 1;
    
    return assessments.filter(item => {
      const date = new Date(item.timestamp);
      return date.getFullYear() === targetYear && (date.getMonth() + 1) === targetMonth;
    });
  },
  
  // 长按记录处理
  onLongPressRecord(e) {
    const index = e.currentTarget.dataset.index;
    const record = this.data.assessments[index];
    
    wx.showActionSheet({
      itemList: ['删除记录'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 删除记录
          this.deleteRecord(record);
        }
      }
    });
  },
  
  // 删除记录
  deleteRecord(record) {
    wx.showModal({
      title: '删除记录',
      content: '确定要删除这条风险评估记录吗？此操作不可恢复。',
      confirmColor: '#ff5a5f',
      success: (res) => {
        if (res.confirm) {
          console.log('用户确认删除记录:', record);
          
          // 调用API删除记录
          healthApi.deleteRiskAssessment(record._id)
            .then(() => {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 重新加载数据
              this.loadAssessments();
            })
            .catch(err => {
              console.error('删除记录失败:', err);
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 查看评估详情
  viewDetail(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedRisk: this.data.assessments[index],
      showDetail: true
    });
  },
  
  // 关闭详情弹窗
  closeDetail() {
    this.setData({
      showDetail: false
    });
  },
  
  // 跳转到健康管理页
  goToHealth() {
    wx.switchTab({
      url: '/pages/health/health'
    });
  },
  
  // 跳转到风险评估页
  goToRiskAssessment() {
    wx.navigateTo({
      url: '/pages/riskAssessment/riskAssessment'
    });
  },
  
  // 页面下拉刷新事件
  onPullDownRefresh: function() {
    console.log('下拉刷新触发，重新加载数据...');
    this.loadAssessments().then(() => {
      // 停止下拉刷新
      wx.stopPullDownRefresh();
    }).catch(error => {
      console.error('刷新数据失败:', error);
      // 确保下拉刷新动画停止
      wx.stopPullDownRefresh();
      
      // 显示错误提示
      wx.showToast({
        title: '刷新数据失败',
        icon: 'none',
        duration: 2000
      });
    });
  }
});
